class User < ActiveRecord::Base
  include Permissions
  
  has_many :designations
  has_one :project, :foreign_key => "owner_id"
  has_many :projects, :through => :designations
  has_many :milestones
  has_many :activities, :foreign_key => "responsible_id"
  has_many :comments
  has_many :logs
  
  validates_presence_of :email
  validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i
  validates_uniqueness_of :email
  
  validates_presence_of :name, :password, :timezone, :locale, :if => :active?
  
  validates_confirmation_of :password, :if => :active?, :on => :create
  validates_confirmation_of :password, :if => :password_changed?, :on => :update
  validates_presence_of :password_confirmation, :if => :password_changed?
  validates_length_of :password, :within => 8..50, :if => :active?

  before_save :encrypt_password
  
  def encrypt_password
    self.password = Digest::MD5.hexdigest(self.password) if self.password and password_changed?
  end
  
  def generate_password(size = 10)
    chars = (('a'..'z').to_a + ('0'..'9').to_a) - %w(i o 0 1 l 0)
    (1..size).collect{ |a| chars[rand(chars.size)] }.join
  end
  
  def generate_password!(size = 10)
    self.password = generate_password(size)
  end
  
  def to_s
    name || email
  end
  
  def admin?(project)
    designations.find_by_project_id(project.id).admin?
  end
  
  def admin_actions
    [
    "projects_edit", 
    "projects_update",
    "permissions_index",
    "permissions_bulk_edit",
    "permissions_destroy"
    ]
  end
  
end